import { isPlainObject } from '../share/utils'
let createConfig
try {
  createConfig = require('uni-config-center')
} catch (error) {
  throw new Error('Plugin[uni-config-center] was not found')
}

/**
 * 基类继承全部需要在 constructor 中调用 super()
 */
export class UniCaptcha {
  constructor () {
    this.pluginConfig = {}
    this._initConfig()
    this._initScene()
  }

  _initConfig () {
    const pluginConfig = createConfig({
      pluginId: 'uni-captcha'
    })
    if (pluginConfig && pluginConfig.hasFile('config.json')) {
      try {
        const config = pluginConfig.config()
        if (isPlainObject(config)) this.pluginConfig = config
      } catch (error) {
        throw new Error(this.t('config-file-invalid') + '\n' + error.messages)
      }
    }
  }

  /**
   * 支持如下配置
   * {
   *   "width":150,
   *   "scene":{
   *     "login":{
   *         "width":150
   *      }
   *   }
   *   ......,
   * }
   */
  _initScene () {
    if (isPlainObject(this.pluginConfig.scene)) {
      const { scene, ...otherConfig } = this.pluginConfig
      Object.keys(scene).forEach(sceneKey => {
        if (scene.scene) delete scene.scene
        this.pluginConfig.scene[sceneKey] = Object.assign({}, otherConfig, scene[sceneKey])
      })
    }
  }
}
